package com.ThreadImp;
//多个线程同时操作一个对象
//购票例子
public class TestThread3 implements Runnable{
    //票数
    private int ticket =10;
    boolean flag = true;
    @Override
    public void run() {
        while (flag){
            buy();
            try{
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        TestThread3 testThread3 = new TestThread3();
        //对象代理开启线程
        new Thread(testThread3,"A").start();
        new Thread(testThread3,"B").start();
        new Thread(testThread3,"C").start();
//        new Thread(()-> System.out.println("123")).start();

    }
    //锁方法  一次只能有一个线程进入该方法 当前线程执行完后别的线程才能进入
    private synchronized void buy(){
        System.out.println(Thread.currentThread().getName()+"拿到票号："+ ticket--);
        if (ticket<=0){
            flag=false;
        }
    }

}

